import React, { useEffect, useState } from 'react';
import PaymentSection from '@/features/pay/components/PaymentSection';
import SearchSection from '@/features/pay/components/SearchSection';
import { Button, message, Modal } from 'antd';
import styles from '../../pages/pay/index.module.css';
import { fetchPaymentOptions, submitRecharge, PaymentOption } from '@/features/pay/services/payment';
import { useWechatJSSDK, callWechatPay } from '@/utils/wechatPay';
import { searchUser } from '@/features/pay/services/userSearch';
import { getAssetPath } from '@/utils/assetPath';

// 支付状态类型定义
interface PayStatus {
  visible: boolean;
  success?: boolean;
  message?: string;
}

// 用户搜索结果类型
interface UserInfo {
  id?: number;
  phone: number;
  nickname: string;
  avatar: string;
}

const PayPageClient: React.FC = () => {
  const [paymentOptions, setPaymentOptions] = useState<PaymentOption[]>([]);
  const [selectedOptionIndex, setSelectedOptionIndex] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const [payStatus, setPayStatus] = useState<PayStatus>({ visible: false });
  const [searchResults, setSearchResults] = useState<UserInfo>({ 
    id: undefined,
    phone: 18730555555, 
    nickname: '暂未选定用户', 
    avatar: getAssetPath('/pay/avatar1.png') 
  });
  
  // 初始化微信JSSDK
  useWechatJSSDK();

  // 加载充值选项
  const loadPaymentOptions = async () => {
    try {
      const options = await fetchPaymentOptions();
      setPaymentOptions(options);
    } catch (error) {
      console.error('加载充值选项失败:', error);
      message.error('加载充值选项失败，请刷新页面重试');
    }
  };

  // 处理URL支付回调
  const handlePaymentCallback = () => {
    if (typeof window === 'undefined') return;
    
    const urlParams = new URLSearchParams(window.location.search);
    const payResult = urlParams.get('pay_result');
    
    const resultMessages = {
      success: '支付成功，钻石已添加到您的账户！',
      fail: '支付失败，请重试',
      cancel: '支付已取消'
    };
    
    if (payResult && payResult in resultMessages) {
      setPayStatus({
        visible: true,
        success: payResult === 'success',
        message: resultMessages[payResult as keyof typeof resultMessages]
      });
    }
  };

  useEffect(() => {
    loadPaymentOptions();
    handlePaymentCallback();
  }, []);

  // 处理微信支付调用
  const handleWechatPay = async (payParams: any) => {
    try {
      console.log('正在调起微信支付...', payParams);
      
      const payResult = await callWechatPay({
        appId: payParams.appId,
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType || 'RSA',
        paySign: payParams.paySign
      });
      
      // 设置支付状态
      setPayStatus({
        visible: true,
        success: (payResult as any).success,
        message: (payResult as any).success 
          ? '支付成功，钻石已添加到您的账户！' 
          : ((payResult as any).message || '支付未完成')
      });
      
    } catch (error: any) {
      console.error('微信支付调用失败:', error);
      setPayStatus({
        visible: true,
        success: false,
        message: error.message || '调起支付失败，请重试'
      });
    }
  };

  // 处理用户搜索
  const handleUserSearch = async (phoneNumber: string): Promise<void> => {
    try {
      const response = await searchUser(phoneNumber);
      console.log(response);
      
      if (response.code === 0 && response.data) {
        setSearchResults({
          id: response.data.user_id,
          phone: 'phone' in response.data ? Number(response.data.phone) : 0,
          nickname: response.data.nickname,
          avatar: (response.data.thumbnails && response.data.thumbnails.length > 0) 
          ? response.data.thumbnails[0] 
          : getAssetPath('/pay/avatar1.png') // 默认头像    
        });
        message.success('用户搜索成功');
      } else {
        message.error(response.msg || '未找到该手机号对应的用户');
      }
    } catch (error: any) {
      console.error('用户搜索失败:', error);
      message.error(error.message || '用户搜索失败，请重试');
      throw error;
    }
  };

  // 确认充值
  const handleConfirmRecharge = async () => {
    // 检查是否已搜索到用户
    if (!searchResults.id) {
      message.warning('请先搜索并选择一个有效用户');
      return;
    }
    
    if (selectedOptionIndex === null) {
      message.warning('请选择一个充值选项');
      return;
    }

    const urlParams = new URLSearchParams(window.location.search);
    const openid = urlParams.get('openid');
    
    if (!openid) {
      message.error('缺少必要的openid参数');
      return;
    }
    
    setLoading(true);
    
    try {
      const selectedOption = paymentOptions[selectedOptionIndex];
      const preParams = {
        openid: openid, // 微信open_id
        user_id: searchResults.id, // 使用搜索到的用户ID
        phone: searchResults.phone, // 使用搜索到的用户ID
        rule_id: selectedOption.rule_id,
        pay_type: selectedOption.pay_type,
        plat_type: selectedOption.plat_type
      }
      
      console.log('预充值请求参数，响应数据:', preParams);
      // 提交充值请求到后端
      const response = await submitRecharge(preParams);
      const {code, data } = response || {};
      console.log('预充值请求成功，响应数据:', data);

      if (code == 200 && data) {
        // 处理微信支付参数
        const pay_params = data.expend.pay_info;
        await handleWechatPay(pay_params);
      } else {
        const errorMsg = typeof data === 'object' && data !== null && 'message' in data
          ? (data as { message?: string }).message
          : undefined;
        message.error(errorMsg || '创建订单失败');
      }
    } catch (error) {
      console.error('充值请求发送失败:', error);
      message.error('网络错误，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 关闭支付结果弹窗
  const closePayStatusModal = () => setPayStatus({ visible: false });

  return (
    <div className={styles.container}>
      {/* 上半部分 */}
      <SearchSection 
        searchResults={searchResults} 
        onSearch={handleUserSearch} 
      />

      {/* 下半部分 */}
      <PaymentSection
        paymentOptions={paymentOptions}
        selectedOptionIndex={selectedOptionIndex}
        setSelectedOptionIndex={setSelectedOptionIndex}
      />

      {/* 确认充值按钮 */}
      <Button
        type="primary"
        block
        onClick={handleConfirmRecharge}
        className={styles.confirmBtn}
        loading={loading}
        disabled={!searchResults.id || selectedOptionIndex === null}
      >
        确认充值
      </Button>
      
      {/* 支付结果提示 */}
      <Modal
        title={payStatus.success ? "支付成功" : "支付提示"}
        open={payStatus.visible}
        onOk={closePayStatusModal}
        onCancel={closePayStatusModal}
        footer={[
          <Button key="back" onClick={closePayStatusModal}>
            {payStatus.success ? '我知道了' : '关闭'}
          </Button>
        ]}
      >
        <p>{payStatus.message}</p>
      </Modal>
    </div>
  );
};

export default PayPageClient;